﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

using kwzx.Data;
using kwzx.Common;

namespace kwzx
{
    public partial class frmGetCard : Form
    {
        public frmGetCard()
        {
            InitializeComponent();
        }




        IDCard card = new IDCard();
        private void CheckGather1_Load(object sender, EventArgs e)
        {
            string newPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "img");
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            card.Init();
        }





        /// <summary>2011-7-5
        /// 将文件转换成二进制
        /// </summary>
        /// <param name="fpath">文件的绝对路径</param>
        /// <returns></returns>
        private byte[] FileToBinary(string fpath)
        {
            FileStream fs = new FileStream(fpath, FileMode.Open, FileAccess.Read);
            int fileLength = Convert.ToInt32(fs.Length);
            byte[] fileBytes = new byte[fileLength];
            BinaryReader br = new BinaryReader(fs);
            for (int i = 0; i < fileLength; i++)
            {
                br.Read(fileBytes, 0, fileLength);
            }
            br.Close();
            fs.Close();
            return fileBytes;
        }







        private void cboGetCard_CheckedChanged(object sender, EventArgs e)
        {
            this.labDLName.Visible = true;
            this.txtGrantedNum.Visible = true;
        }

        private void btnReadCard_Click(object sender, EventArgs e)
        {

            string msg = "";
            IDCard.IDCardData cardMsg = new IDCard.IDCardData();
            cardMsg = card.ReadCard(ref msg);
            if (cardMsg.Name != "")
            {
                this.picUser.Image = null;
                txtUserName.Text = cardMsg.Name;
                txtSex.Text = cardMsg.Sex == "1" ? "男" : "女";
                txtIndentity.Text = cardMsg.IDCardNo;
                txtAddress.Text = cardMsg.Address;
                string CardPath = cardMsg.PhotoFileName;
                //if (this.picUser.Image != null)
                //{
                //    picUser.Image.Dispose();
                //    picUser.Image = null;
                //    File.Delete(CardPath);
                //}
                if (File.Exists(CardPath))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(CardPath);
                    System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
                    picUser.Image = bmp;
                    img.Dispose();

                }
                using (HXYKTEntities db = new HXYKTEntities())
                {

                    //如果身份证号码在T_User_sfz没有  则是第一次录入    
                    var user = db.T_User_sfz.Where(a => a.UserNum == cardMsg.IDCardNo).FirstOrDefault();
                    if (user == null)
                    {
                        user = new T_User_sfz();
                        user.UserNum = cardMsg.IDCardNo;
                        user.UserName = cardMsg.Name;
                        user.Sex = cardMsg.Sex;
                        user.Address = cardMsg.Address;
                        user.Pic = FileToBinary(cardMsg.PhotoFileName);
                        user.Date = DateTime.Now;
                        user.GatherState = false;
                        user.GetCardState = false;
                        db.AddToT_User_sfz(user);
                        db.SaveChanges();
                    }

                    //如果该身份证在T_USER存在则把他的基本信息拿出来进行比较
                    var userInfo = db.T_USER.Where(a => a.sfzh == user.UserNum).FirstOrDefault();
                    if (userInfo != null)
                    {
                        int deptid = (int)userInfo.DEPT_id;
                        var deptname = (db.T_BM.Where(a => a.DEPT_id == deptid).FirstOrDefault()).BMMC;
                        txtDept.Text = deptname.ToString();
                        txtUser1.Text = userInfo.ZSXM;
                        txtXB.Text = userInfo.XB;
                        txtID.Text = userInfo.sfzh;
                        txtPhone.Text = userInfo.DH;
                        txtPersonNum.Text = userInfo.rybh;
                        string Imgpath = userInfo.ZP;
                        if (!string.IsNullOrWhiteSpace(Imgpath))
                        {
                            int x = Imgpath.IndexOf("ftp/") + 4;
                            string userImg = Imgpath.Substring(x, Imgpath.Length - x);   //ftp下载路径
                            // 路径为:DBFZSPersonImg/李瑞明131684197012105231.jpg
                            int userImginfo = userImg.IndexOf("/") + 1;
                            string spath = SPicUtils.path + userImg.Substring(0, userImg.IndexOf("/")) + "\\";
                            FileTran.DownloadFile(spath, "", userImg);
                            string imgname = userImg.Substring(userImginfo, (userImg.Length - userImginfo));
                            
                            this.picUser2.Image = SPicUtils.PicConvert(spath + imgname);

                        }
                        // txtPersonType.Text = GetUserType(userInfo.RY_ID);  //人员类别为外键 需要找到Name
                        txtCompanyName.Text = userInfo.DZ;  //公司简称无字段
                        txtgz.Text = GetDETAIL(userInfo.gz);  //工种为外键，需要找到Name
                        //txtzc.Text = GetDETAIL(userInfo.zc);  //职称为外键，需要找到Name
                        //txtxl.Text = userInfo.xl != null ? userInfo.xl.ToString() : ""; //学历
                        //txtbyrq.Text = userInfo.byyx != null ? userInfo.byyx.ToString() : "";
                        //txtbyrq.Text = userInfo.bysj != null ? userInfo.bysj.ToString() : "";
                        //txtrzrq.Text = userInfo.rzrq != null ? userInfo.rzrq.ToString() : "";
                        txttsNum.Text = userInfo.tsgzzjhm != null ? userInfo.tsgzzjhm.ToString() : "";
                        txtyxq.Text = userInfo.tszjyxq != null ? userInfo.tszjyxq.ToString() : "";
                        txtfsq.Text = userInfo.tszjfsrq != null ? userInfo.tszjfsrq.ToString() : "";
                        txtbzrq.Text = userInfo.bzrq != null ? userInfo.bzrq.ToString() : "";
                    }
                    string UserNum = cardMsg.IDCardNo;
                    string sql = string.Format("select * from 人员信息 where 身份证号码 ='{0}'", UserNum);
                    DataTable dt = DBAccHelper.GetDataSet(sql);
                    if (dt.Rows.Count > 0)
                    {
                        MessageBox.Show("此人属于在逃疑犯");
                    }
                    File.Delete(CardPath);
                }
            }
            else
            {
                this.picUser.Image = null;
                txtUserName.Text = "";
                txtSex.Text = "";
                txtIndentity.Text = "";
                txtAddress.Text = "";
            }

        }

        public string GetDETAIL(int? detailID)
        {
            string result = "";
            using (HXYKTEntities db = new HXYKTEntities())
            {
                var modle = (db.X_CS_DETAIL.Where(a => a.DETAIL_ID == detailID).FirstOrDefault());
                if (modle != null || modle.MC != "")
                {
                    result = modle.MC;
                }

            }
            return result;
        }


        public string GetUserType(int? typeID)
        {
            string result = "";
            using (HXYKTEntities db = new HXYKTEntities())
            {
                var modle = (db.CD_UserType.Where(a => a.RY_ID == typeID).FirstOrDefault());
                if (modle != null || modle.RY_Name != "")
                {
                    result = modle.RY_Name;
                }

            }
            return result;
        }



        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtIndentity.Text != "")
            {
                T_User_LY user = new T_User_LY();
                user.UserNum = txtIndentity.Text;
                user.GatherDate = DateTime.Now;
                user.Operater = kwzx.Utils.CurrentUser.xm;
                user.ISCome = true;
                user.StateType = "领取卡片";
                user.DLRName = txtGrantedNum.Text;   //代领人姓名

                using (HXYKTEntities db = new HXYKTEntities())
                {
                    //如果该身份证在T_USER存在则把他的基本信息拿出来进行比较
                    T_USER userInfo = db.T_USER.Where(a => a.sfzh == user.UserNum).FirstOrDefault();

                    userInfo.DH = txtPhone.Text;
                    userInfo.rybh = txtPersonNum.Text;
                    userInfo.tsgzzjhm = txttsNum.Text;
                    if (txtrzrq.Text != "")
                    {
                        userInfo.rzrq = Convert.ToDateTime(txtrzrq.Text);
                    }

                    if (txtyxq.Text != "")
                    {
                        userInfo.tszjyxq = Convert.ToDateTime(txtyxq.Text);
                    }
                    if (txtfsq.Text != "")
                    {
                        userInfo.tszjfsrq = Convert.ToDateTime(txtfsq.Text);
                    }
                    db.SaveChanges();

                }
                if (SaveData(user) > 0)
                {
                    picUser.Image = global::kwzx.Properties.Resources.无图片; ;
                    picUser2.Image = global::kwzx.Properties.Resources.无图片; ;

                    ClearText();
                }
            }
        }

        private void ClearText()
        {

            foreach (var item in this.Controls)
            {
                GroupBox gr = item as GroupBox;
                if (gr != null)
                {
                    foreach (var item1 in gr.Controls)
                    {
                        TextBox tb = item1 as TextBox;
                        if (tb != null)
                        {
                            tb.Text = "";
                        }
                    }
                }

            }
        }


        private void btnCancle_Click(object sender, EventArgs e)
        {
            if (txtIndentity.Text != "")
            {
                T_User_LY user = new T_User_LY();
                user.UserNum = txtIndentity.Text;
                user.GatherDate = DateTime.Now;
                user.Operater = kwzx.Utils.CurrentUser.xm;
                user.ISCome = false;
                user.Reson = txtReson.Text;

                user.StateType = "领取卡片";
                user.DLRName = txtGrantedNum.Text;   //代领人姓名


                if (SaveData(user) > 0)
                {
                    picUser.Image = global::kwzx.Properties.Resources.无图片; ;
                    picUser2.Image = global::kwzx.Properties.Resources.无图片; ;
                    ClearText();
                }
            }
        }



        private int SaveData(T_User_LY user)
        {
            int num = 0;
            using (HXYKTEntities db = new HXYKTEntities())
            {
                db.AddToT_User_LY(user);
                num = db.SaveChanges();
            }
            return num;
        }








    }
}
